package com.mjlf.ticket.robort;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName AirPort
 * @auther mjlf
 * @Date 2019/6/19 10:51
 * @Description TODO
 */
public class AirPort{

    private Map<String, Integer> ticket = new HashMap<>();

    public String getTicket(String name){
        if(ticket.containsKey(name)){
            synchronized (this){
                int num = ticket.get(name);
                if(num <= 1){
                    return null;
                }
                String result = name + "-" + num;
                ticket.put(name, num-1);
                return result;
            }
        }
        return null;
    }

    static class Company implements Runnable{
        private AirPort airPort;
        private String name;

        public Company(AirPort airPort, String name) {
            this.airPort = airPort;
            this.name = name;
        }

        @Override
        public void run() {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String ticket = airPort.getTicket(name);
                System.out.println(Thread.currentThread().getName() + " : " + ticket);
            }
        }
    }

    public static void main(String[] args) {
        AirPort airPort = new AirPort();
        airPort.ticket.put("bj-sh", 20);
        airPort.ticket.put("bj-xm", 25);
        airPort.ticket.put("bj-gd", 24);

        Thread t1 = new Thread(new Company(airPort, "bj-sh"));
        Thread t2 = new Thread(new Company(airPort, "bj-sh"));
        Thread t3 = new Thread(new Company(airPort, "bj-sh"));

        t1.start();
        t2.start();
        t3.start();
    }
}
